chrome.runtime.onInstalled.addListener(() => {
  console.log('Service Worker 注册成功');
});

chrome.action.onClicked.addListener((tab) => {
  console.log('Extension icon clicked');
  if (!tab.id) {
    console.error('No tab ID found.');
    return;
  }
  attachDebugger(tab.id);
});

// 用于存储多个 tab 的调试信息和状态
const tabDebuggers = {};

async function attachDebugger(tabId) {
  if (tabDebuggers[tabId]) {
    console.warn(`Debugger is already attached to tab ${tabId}`);
    return;
  }

  try {
    // 在附加调试器前，先尝试分离已存在的调试器（避免冲突）
    await chrome.debugger.detach({ tabId });
  } catch (error) {
    console.warn(`未找到已附加的调试器，跳过分离操作 - Tab ID: ${tabId}`);
  }

  try {
    await chrome.debugger.attach({ tabId }, "1.3");
    console.log(`Debugger attached to tab ${tabId}`);

    await chrome.debugger.sendCommand({ tabId }, "Network.enable");

    // 为每个 tab 初始化相关的数据存储
    tabDebuggers[tabId] = {
      wsConnections: {}, // 存储 WebSocket 连接信息
      pendingRequests: {}, // 存储 HTTP 请求信息
      reconnectInterval: setInterval(() => {
        console.log(`Performing periodic reconnect for tab ${tabId}`);
        attachDebugger(tabId);
      }, 5 * 60 * 1000), // 5分钟自动重连
    };

    chrome.debugger.onEvent.addListener(async (source, method, params) => {
      if (source.tabId !== tabId) return; // 仅处理当前 tab 的事件

      const { wsConnections, pendingRequests } = tabDebuggers[tabId];

      /*
      监控 WebSocket
      */
      if (method === "Network.webSocketCreated") {
        wsConnections[params.requestId] = params.url;
        console.log(`WebSocket created in tab ${tabId}:`, params.url);
      }

      if (method === "Network.webSocketFrameReceived" || method === "Network.webSocketFrameSent") {
        const wsUrl = wsConnections[params.requestId];
        if (wsUrl) {
          const messageType = method === "Network.webSocketFrameReceived" ? "received" : "sent";
          sendToApi(params.response.payloadData, messageType, wsUrl);
        }
      }

      /*
      监控 HTTP 请求和响应
      */
      if (method === "Network.requestWillBeSent" && params.request.url.includes('http')) {
        console.log(`监控到 HTTP 请求 in tab ${tabId}:`, params.request.url, params.type);
        if (params.type === "XHR" || params.type === "Fetch") {
          pendingRequests[params.requestId] = {
            url: params.request.url,
            requestData: params.request.postData || "无请求数据",
            requestTimestamp: Date.now()
          };
        }
      }

      // 捕获 HTTP 响应
      if (method === "Network.responseReceived" && pendingRequests[params.requestId]) {
        const responseBody = await retryGetResponseBody(source, params.requestId);
        if (responseBody) {
          const requestInfo = pendingRequests[params.requestId];
          const mergedData = {
            request: {
              data: requestInfo.requestData,
              timestamp: requestInfo.requestTimestamp
            },
            response: {
              data: responseBody,
              timestamp: Date.now()
            }
          };

          console.log(`合并的 HTTP 数据 in tab ${tabId}:`, requestInfo.url, mergedData);
          sendToApi(JSON.stringify(mergedData), 'xhr', requestInfo.url);

          // 完成后清除请求记录
          delete pendingRequests[params.requestId];
        } else {
          console.warn(`未能获取到响应内容 in tab ${tabId}:`, params.requestId);
        }
      }
    });

  } catch (error) {
    console.error(`Failed to attach debugger to tab ${tabId}:`, error);
  }
}

// 处理关闭标签页时的清理工作
chrome.tabs.onRemoved.addListener((tabId) => {
  if (tabDebuggers[tabId]) {
    clearInterval(tabDebuggers[tabId].reconnectInterval);
    delete tabDebuggers[tabId];
    console.log(`Debugger detached from tab ${tabId} and resources cleaned up`);
  }
});

// sendToApi 和 retryGetResponseBody 代码保持不变，直接复用

async function sendToApi(data, type, url) {
  const apiUrl = 'https://yunlvltd.com/app-api/vote/test/println'; // 替换为你的 API URL
  try {
    const payload = {
      type: type,
      url: url,
      data: data,
      timestamp: Date.now()
    };

    const response = await fetch(apiUrl, {
      method: 'POST',
      headers: {
        'Content-Type': 'application/json',
        'Tenant-Id': '1'
      },
      body: JSON.stringify(payload)
    });
    if (!response.ok) {
      throw new Error(`Network response was not ok: ${response.statusText}`);
    }
  } catch (error) {
    console.error("Failed to send data to API:", error, url);
  }
}

async function retryGetResponseBody(source, requestId, retryCount = 3, delay = 500) {
  while (retryCount > 0) {
    try {
      const response = await new Promise((resolve, reject) => {
        chrome.debugger.sendCommand(source, "Network.getResponseBody", { requestId }, (result) => {
          if (chrome.runtime.lastError || !result) {
            reject(chrome.runtime.lastError || "No data found");
          } else {
            resolve(result);
          }
        });
      });
      return response;
    } catch (error) {
      console.warn(`Retry ${3 - retryCount + 1} failed for requestId ${requestId}:`, error);
      retryCount--;
      await new Promise((resolve) => setTimeout(resolve, delay)); // 延迟后重试
    }
  }
  return null; // 所有重试失败后返回 null
}
